package com.milk.controller.user;

import com.milk.constant.JwtClaimsConstant;
import com.milk.dto.UserLoginDTO;
import com.milk.entity.User;
import com.milk.properties.JwtProperties;
import com.milk.result.Result;
import com.milk.service.UserService;
import com.milk.utils.JwtUtil;
import com.milk.vo.UserLoginVO;
import com.milk.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user/user")
@ApiModel(value = "用户信息接口")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;


    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("微信登录")
    public Result<UserLoginVO> wxLogin(@RequestBody UserLoginDTO userLoginDTO){
        //微信登录
        User user = userService.wxLogin(userLoginDTO);
        //生成JWT令牌
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("userId",user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        //封装
        UserLoginVO build = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();
        return Result.success(build);
    }

    /**
     * 查询个人信息
     * @return
     */
    @GetMapping
    @ApiModelProperty("查询个人信息")
    public Result<UserVO> selectInfo(){
        UserVO user = userService.selectInfo();
        return Result.success(user);
    }

    /**
     * 修改个人信息
     * @param user
     * @return
     */
    @PostMapping
    @ApiModelProperty("修改个人信息")
    public Result updateById(@RequestBody User user){
        userService.updateUser(user);
        return Result.success();
    }

}
